<template>
  <a-modal
    v-model:open="state.dialog.isShowDialog"
    width="1000px"
    style="height: 600px"
    centered
    :title="state.dialog.title"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div>
      <div>
        请从MCP
        Servers的介绍页面复制配置JSON（优先使用NPX或UVX配置），并粘贴到输入框中
      </div>
      <div>
        <Ace
          v-model="mcp_json"
          style="width: 100%; height: 300px"
          ref="myEditor"
        ></Ace>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, defineAsyncComponent, ref } from 'vue';
  import { useToolsApi } from '@/api/tools';
  import { message } from 'ant-design-vue';

  const toolsApi = useToolsApi();
  const Ace = defineAsyncComponent(() => import('@/components/ace.vue'));
  const mcp_json = ref('');
  // 定义子组件向父组件传值/事件
  const emits = defineEmits(['refresh']);

  const state = reactive({
    dialog: {
      isShowDialog: false,
      title: '从JSON导入',
    },
  });

  const openDialog = () => {
    state.dialog.isShowDialog = true;
  };

  // 数据提交方法
  const handleSubmit = async () => {
    try {
      const cleanJsonString = mcp_json.value.replace(/[\r\n]/g, '');
      const mcpObject = JSON.parse(cleanJsonString);
      const res = await toolsApi.createTool(mcpObject);
      message.success('创建成功');
      state.dialog.isShowDialog = false;
      emits('refresh');
    } catch (error) {
      message.error('创建失败');
    }
  };
  const handleCancel = () => {
    mcp_json.value = '';
  };
  // 暴露变量
  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
